<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="t('service.审核退款申请')"
    width="600px"
    :confirmLoading="confirmLoading"
  >
    <div class="h-500 overflow-y-auto">
      <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
        <!-- 仅退款申请审核，退货退款申请审核 -->
        <template
          v-if="
            detail.refundAskType == 1 ||
            (detail.refundAskType == 2 && detail.refundStatus == -2)
          "
        >
          <el-form-item :label="t('service.是否同意申请')">
            <el-radio-group v-model="form.refundStatus">
              <el-radio :label="-3">{{ t('service.同意') }}</el-radio>
              <el-radio :label="-4">{{ t('service.驳回') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            :label="t('service.驳回原因')"
            v-if="form.refundStatus === -4"
            prop="refundCheckRejectReason"
          >
            <el-input
              v-model="form.refundCheckRejectReason"
              type="textarea"
              :rows="3"
              :placeholder="t('service.请输入')"
            />
          </el-form-item>
        </template>
        <!-- 仅退款申请审核，退货退款确认收货状态时 -->
        <template
          v-if="
            detail.refundAskType == 1 ||
            (detail.refundAskType == 2 && detail.refundStatus == -5)
          "
        >
          <el-form-item :label="t('service.退款金额')" v-if="form.refundStatus === -3">
            <div>
              <el-input-number
                v-model="form.refundCheckPayTotal"
                :min="0"
                :max="refundRealTotal"
                style="width: 100%"
              />
              <div class="fs-12 color-666666">
                {{ t('service.请输入退款金额，最多') }}{{ refundRealTotal }}{{ t("currency.元") }}。{{ t('service.商品实付金额') }}{{
                  refundRealSku
                }}{{ t('currency.元') }}；{{ t('service.商品运费金额') }}{{ refundRealPostage }}{{ t("currency.元") }}；{{
                  t("service.总实付金额") 
                }}{{ refundRealTotal }}{{ t('currency.元') }}
              </div>
            </div>
          </el-form-item>
        </template>

        <!-- 退货退款 且为 同意状态时 -->
        <el-form-item
          :label="t('service.商家收货地址')"
          v-if="
            form.refundStatus === -3 &&
            detail.refundAskType == 2 &&
            detail.refundStatus == -2
          "
        >
          <div class="address flex1">
            <div
              class="address-item flex_aic cursor-pointer"
              :class="{ active: form.refundCheckAddressId === item.id }"
              v-for="item in addressList"
              :key="item.id"
              @click="form.refundCheckAddressId = item.id"
            >
              <el-icon
                size="16"
                :color="
                  form.refundCheckAddressId === item.id ? '#ff7e28' : '#999'
                "
                class="mr10"
                ><CircleCheckFilled
              /></el-icon>
              <div class="flex1 ml10">
                <div class="flex_aic">
                  <span>{{ item["name" + locale] }}</span>
                  <span class="ml10">{{ item["phone"] }}</span>
                </div>
                <div class="address-item-address">
                  {{ item["province" + locale] }} {{ item["city" + locale] }}
                  {{ item["area" + locale] }} {{ item["address" + locale] }}
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </Dialog>
</template>
<script setup>
import { ref, watch, computed, watchEffect } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import { CircleCheckFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const { locale, t } = useI18n();  
const show = defineModel();
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(["rest"]);
const addressList = ref([]);
const refundRealTotal = ref(0);
const refundRealPostage = ref(0);
const refundRealSku = ref(0);
const refundAskPayTotal = ref("");
const confirmLoading = ref(false);

watchEffect(() => {
  const { saleSkus } = props.detail || [];
  const payRealSku = saleSkus?.reduce((acc, curr) => {
    return acc + curr.payRealSku;
  }, 0);
  const skuPostage = saleSkus?.reduce((acc, curr) => {
    return acc + curr.skuPostage * curr.refundSkuCount;
  }, 0);
  refundRealTotal.value = (payRealSku + skuPostage).toFixed(2);
  refundRealSku.value = payRealSku;
  refundRealPostage.value = skuPostage;
  refundAskPayTotal.value = props.detail?.refundAskPayTotal;
});
const form = ref({
  refundStatus: -3,
  refundCheckRejectReason: "",
  refundCheckAddressId: "",
  refundCheckPayTotal: refundAskPayTotal, //  这里先取用户申请的退款金额
});
const rules = {
  refundCheckRejectReason: [
    { required: true, message: t('service.请输入驳回原因'), trigger: "blur" },
  ],
};
const formRef = ref();
watch(show, (val) => {
  if (val) {
    getAddressList();
  }
});
const handleSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      confirmLoading.value = true;

      const callback = (res) => {
        if (res.status === 200) {
          ElMessage.success(t('service.操作成功'));
          show.value = false;
          emit("rest");
        }
      };

      // 仅退款申请审核
      if (props.detail.refundAskType == 1) {
        Api.refundCheck({
          id: props.detail.id,
          refundStatus: form.value.refundStatus,
          refundCheckRejectReason: form.value.refundCheckRejectReason,
          refundCheckPayTotal: form.value.refundCheckPayTotal,
        })
          .then((res) => {
            callback(res);
          })
          .finally(() => {
            confirmLoading.value = false;
          });
      }

      // 退货退款 审核申请
      if (props.detail.refundAskType == 2 && props.detail.refundStatus == -2) {
        Api.refundCheck({
          id: props.detail.id,
          refundStatus: form.value.refundStatus,
          refundCheckRejectReason: form.value.refundCheckRejectReason,
          refundCheckAddressId: form.value.refundCheckAddressId,
        })
          .then((res) => {
            callback(res);
          })
          .finally(() => {
            confirmLoading.value = false;
          });
      }

      // 仅退款申请审核，确认收货
      if (props.detail.refundAskType == 2 && props.detail.refundStatus == -5) {
        Api.refundSign({
          id: props.detail.id,
          refundCheckPayTotal: form.value.refundCheckPayTotal,
        })
          .then((res) => {
            callback(res);
          })
          .finally(() => {
            confirmLoading.value = false;
          });
      }
    }
  });
};
const close = () => {
  form.value = {
    refundStatus: -3,
    refundCheckRejectReason: "",
    refundCheckAddressId: "",
    refundCheckPayTotal: refundAskPayTotal,
  };
  show.value = false;
};

const getAddressList = () => {
  Api.getTenantAddress({
    page: 0,
    size: 1000,
  }).then((res) => {
    form.value.refundCheckAddressId = res.data?.content?.[0]?.id;
    addressList.value = res.data?.content || [];
  });
};
</script>
<style lang="scss" scoped>
.h-500 {
  height: 500px;
}
.lht-38 {
  line-height: 38px;
}
.w-120 {
  width: 120px;
}
.address {
  .address-item {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-bottom: 10px;
    .address-item-address {
      font-size: 12px;
      color: #999;
    }

    &:hover {
      border-color: #ff7e28;
    }
    &.active {
      border-color: #ff7e28;
    }
  }
}
</style>
